package com.qs.es.service;

import com.alibaba.fastjson2.JSON;
import com.qs.constant.EsConstant;
import com.qs.mapper.GoodsMapper;
import com.qs.mapper.StoreMapper;
import com.qs.pojo.es.EsGoodsDto;
import com.qs.pojo.es.EsStoreDto;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName: EsGoodsService
 * Package: com.qs.es
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2023/12/29 - 10:11
 * @Version: v1.0
 */
@Service
public class EsStoreService {

    @Autowired
    private RestHighLevelClient client;

    /**
     * 批量导入商品数据
     * @param list
     */
    public void bulkStoreGoods(List<EsStoreDto> list) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        list.stream().forEach(store -> {
            bulkRequest.add(new IndexRequest(EsConstant.INDEX_NAME_STORE)
                    .id(store.getKey().toString())
                    .source(JSON.toJSONString(store),XContentType.JSON));
        });
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

    private List<EsStoreDto> handlerStoreLightResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        SearchHit[] hits = searchHits.getHits();
        List<EsStoreDto> list = new ArrayList<EsStoreDto>();
        for(SearchHit hit : hits){
            String json = hit.getSourceAsString();
            EsStoreDto esStoreDto = JSON.parseObject(json, EsStoreDto.class);
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(!CollectionUtils.isEmpty(highlightFields)){
                HighlightField highlightField = highlightFields.get("store");
                if(highlightField != null){
                    String store = highlightField.getFragments()[0].string();
                    esStoreDto.setStore(store);
                }
            }
            list.add(esStoreDto);
        }
        return list;
    }

    /**
     * 新增店铺文档
     * @param esStoreDto
     * @throws IOException
     */
    public void addDocument(EsStoreDto esStoreDto) throws IOException {
        IndexRequest indexRequest = new IndexRequest(EsConstant.INDEX_NAME_STORE).id(esStoreDto.getKey().toString());
        indexRequest.source(JSON.toJSONString(esStoreDto),XContentType.JSON);
        client.index(indexRequest,RequestOptions.DEFAULT);
    }

    /**
     * 删除文档
     * @param list
     * @throws IOException
     */
    public void deleteDocument(List<Integer> list,String indexName) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        list.stream().forEach(id -> {
            bulkRequest.add(new DeleteRequest(indexName,id.toString()));
        });
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }

    /**
     * 删除索引库
     * @throws IOException
     */
    public void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indexName);
        client.indices().delete(deleteRequest,RequestOptions.DEFAULT);
    }

    /**
     * 判断索引库是否存在
     * @return
     * @throws IOException
     */
    public boolean isExits(String indexName) throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
        return client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 搜索店铺
     * @param pageNo
     * @param pageSize
     * @param ids
     * @param msg
     * @return
     * @throws IOException
     */
    public Map<String, Object> searchStoreFrontList(Integer pageNo, Integer pageSize, List<Integer> ids, String msg) throws IOException {
        if(!CollectionUtils.isEmpty(ids)){
            SearchRequest request = new SearchRequest(EsConstant.INDEX_NAME_STORE);
            //根据key查询
            request.source().query(QueryBuilders.termsQuery("key",ids));
            request.source().query(QueryBuilders.multiMatchQuery(msg,"store"));
            //高亮查询完成
            request.source().highlighter(new HighlightBuilder()
                    .field("store")
                    .preTags("<font color='red'>")
                    .postTags("</font>")
                    .requireFieldMatch(false));
            //分页
            request.source().from((pageNo - 1) * pageSize).size(pageSize);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //高亮处理返回数据
            List<EsStoreDto> list = handlerStoreLightResponse(response);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("data",list);
            map.put("total",response.getHits().getTotalHits().value);
            return map;
        }
        return null;
    }
}
